import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Alert,
  TouchableOpacity,
  Image,
  Platform,
} from 'react-native';
import { PhotoFile } from 'react-native-vision-camera';
import CameraView from '../../components/Camera';
import { useARData } from '../../hooks/useARData';

const Main: React.FC = () => {
  const [capturedPhoto, setCapturedPhoto] = useState<PhotoFile | null>(null);

  const { frameProcessor, distance } = useARData();

  const handlePhotoCaptured = (photo: PhotoFile) => {
    setCapturedPhoto(photo);
    console.log('Photo captured:', photo);
  };

  const retakePhoto = () => {
    setCapturedPhoto(null);
  };

  if (capturedPhoto) {
    const imageUrl =
      Platform.OS === 'ios'
        ? capturedPhoto.path
        : 'file://' + capturedPhoto.path;
    return (
      <View style={styles.dataContainer}>
        <Image source={{ uri: imageUrl }} style={styles.capturedImage} />

        <View style={styles.resultContainer}>
          {distance !== null ? (
            <Text style={styles.resultText}>
              测量距离: {distance.toFixed(2)} mm
            </Text>
          ) : (
            <Text style={styles.resultText}>没有测量数据！</Text>
          )}

          <TouchableOpacity
            style={[styles.button, styles.secondaryButton]}
            onPress={retakePhoto}
          >
            <Text style={styles.buttonText}>重新测量</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <CameraView
        onPhotoCaptured={handlePhotoCaptured}
        frameProcessor={frameProcessor}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'black',
  },
  dataContainer: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
  },
  capturedImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
  },
  resultContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 20,
    alignItems: 'center',
  },
  resultText: {
    fontSize: 18,
    color: '#333',
    marginBottom: 20,
  },
  buttonContainer: {
    flexDirection: 'row',
    gap: 10,
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  secondaryButton: {
    backgroundColor: '#2196F3',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default Main;
